package net.wanho.service.impl;

import lombok.SneakyThrows;
import net.wanho.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * Author：汤小洋
 * Date：2025-07-24 13:56
 * Description：<描述>
 */
@Service
public class FileServiceImpl implements FileService {
    /**
     * 本地文件上传路径
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件访问前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 文件访问域名
     */
    @Value("${file.domain}")
    public String domain;

    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file) {
        // 拼接文件上传路径
        String uploadDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String fileName = file.getOriginalFilename();
        fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        File uploadPath = new File(localFilePath + File.separator + uploadDir + File.separator + fileName);

        // 判断文件目录是否存在，不存在则创建
        if (!uploadPath.getParentFile().exists()){
            uploadPath.getParentFile().mkdirs();
        }
        // 保存文件
        file.transferTo(uploadPath);

        // 拼接文件访问地址
        String url = domain + localFilePrefix + "/" + uploadDir + "/" + fileName;
        return url;
    }
}